﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace MicroBlog.Infrastructure
{
    /// <summary>
    /// 异常过滤器
    /// </summary>
    public class BlogExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            #region 返回一个视图
            //var result = new ViewResult { ViewName = "CustomError" };
            //result.ViewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState);
            //result.ViewData.Add("Exception", context.Exception);
            //context.Result = result;
            #endregion
            string msg = context.Exception.Message;
            ContextResult result = ContextResult.Failed(new ContextError
            {
                Code = "400",
                Description = msg
            });
            context.Result = new JsonResult(result);

            //标识异常已处理
            context.ExceptionHandled = true;
        }
    }
}
